package src; /**
 * Created by imyar on 2019/1/30.
 */

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.mapreduce.TableOutputFormat;
import org.apache.hadoop.hbase.mapreduce.TableReducer;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;

import java.io.IOException;
import java.util.StringTokenizer;

public class WordCountHbase {

    public static class TokenizerMapper
            extends Mapper<LongWritable, Text, Text, IntWritable> {

        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();

        @Override
        public void map(LongWritable key, Text value, Context context
        ) throws IOException, InterruptedException {
            StringTokenizer itr = new StringTokenizer(value.toString());
            while (itr.hasMoreTokens()) {
                word.set(itr.nextToken());
                context.write(word, one);
            }
        }
    }

    public static class IntSumReducer
            extends TableReducer<Text, IntWritable, NullWritable> {

        @Override
        public void reduce(Text key, Iterable<IntWritable> values,
                           Context context
        ) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable val : values) {
                sum += val.get();
            }
            Put put = new Put(Bytes.toBytes(key.toString()));
            //put实例化，每一个词存一行
            put.addColumn(Bytes.toBytes("content"), Bytes.toBytes("count"), Bytes.toBytes(String.valueOf(sum)));
            //列族为content，列修饰符尾count，列值为数目
            context.write(NullWritable.get(), put);
        }
    }

    public static void createHBaseTable(String tableStr, Connection connection) throws IOException {
        TableName tablename = TableName.valueOf(tableStr);
        HTableDescriptor htd = new HTableDescriptor(tablename);
        HColumnDescriptor col = new HColumnDescriptor(Bytes.toBytes("content"));
        htd.addFamily(col);
        Admin admin = connection.getAdmin();
        if (admin.tableExists(tablename)) {
            System.out.println("table exists,trying recreate table");
            admin.disableTable(tablename);
            admin.deleteTable(tablename);
        }
        System.out.println("create new table: " + tablename);
        admin.createTable(htd);
        //校验表是否可用
        boolean avail = admin.isTableAvailable(tablename);
        System.out.println("Table available: " + avail);
    }


    public static void main(String[] args) throws Exception {
        String tablename = "wordcount";
        Configuration configuration = HBaseConfiguration.create();
        configuration.set(TableOutputFormat.OUTPUT_TABLE, tablename);
        configuration.set("hbase.zookeeper.property.clientPort", "2181");
        configuration.set("hbase.zookeeper.quorum", "192.168.1.234");
        //集群配置↓
        //configuration.set("hbase.zookeeper.quorum", "101.236.39.141,101.236.46.114,101.236.46.113");
        configuration.set("hbase.master", "192.168.1.234:60000");
        Connection connection = ConnectionFactory.createConnection(configuration);
        createHBaseTable(tablename, connection);

        Job job = Job.getInstance(configuration, "word count");
        job.setJarByClass(WordCountHbase.class);
        job.setNumReduceTasks(3);
        job.setMapperClass(TokenizerMapper.class);
        job.setReducerClass(IntSumReducer.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TableOutputFormat.class);

        FileInputFormat.addInputPath(job, new Path(args[0]));
//        FileOutputFormat.setOutputPath(job, new Path(args[1]));
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}